<!--
 * @Description: 
 * @Version: 2.0
 * @Autor: zhangjx
 * @Date: 2023-05-26 19:02:57
 * @LastEditors: uphldjx 1373577124@qq.com
 * @LastEditTime: 2024-07-12 09:29:25
-->
<template>
	<div class="ap-container" id="ap-container">
		<p v-if="isComprehensiveQueries">
			<span class="mr8">当前数据总量:</span>
			<span class="text-primary">{{ pageReac.total }}</span>
		</p>
		<el-card class="box-card mt10" shadow="hover" v-if="searchConfig && !isComprehensiveQueries">
			<template #header>
				<div class="ap-header flex align-center" v-if="showHeaderTitle">
					<slot v-if="slotAttr.pageName" name="pageName"></slot>
					<p class="mr8 text-title-page" v-else>{{ route.meta?.title || pageName }}</p>
					<div class="fc text-title-page">
						<slot v-if="slotAttr.pageTitle" name="pageTitle" :total="pageReac.total"></slot>
						<template v-else>
							<span class="mr8">当前数据总量:</span>
							<span class="text-primary">{{ pageReac.total }}</span>
						</template>
						<slot name="title-right"></slot>
					</div>
					<div v-if="needPigeonhole" class="pigeonhole_part">
						<div style="width: 220px; margin-left: 100px">
							<el-button @click="allExport">全部导出</el-button>
							<el-button @click="toDataStatistics">数据统计</el-button>
						</div>

						<label style="width: 100px" for="time">归档时间：</label>
						<DateBetween
							dateType="datetimerange"
							format="YYYY-MM-DD HH:mm:ss"
							valueFormat="YYYY-MM-DD HH:mm:ss"
							v-model="pigeonholeTime"
							@update:modelValue="handleTimeChange"
						></DateBetween>
					</div>
				</div>
				<slot name="header-item"></slot>
			</template>
			<div class="ap-search">
				<slot name="search"></slot>
				<div class="flex align-center">
					<AplidForm
						v-model="searchModel"
						v-bind="searchConfig"
						ref="searchRef"
						:showBtn="false"
						:showRules="false"
						@reset="onReset"
						@submit="onSearch"
					>
						<template v-for="(_, key) in slotAttr" v-slot:[key]="{ row }">
							<slot :name="key" :row="row" :model="searchModel"></slot>
						</template>
					</AplidForm>
					<div class="operate" style="margin-bottom: 18px">
						<el-button type="primary" :icon="Search" @click="searchRef!.onSubmit()"> 搜索 </el-button>
						<el-button class="ap-btn" :icon="Refresh" @click="searchRef!.onReset()"> 重置 </el-button>
						<el-button text @click="drawer = !drawer" v-if="moreSearchConfig">
							<div class="flex-nwrap">
								<span>展开</span>
								<icon-expand-left theme="outline" size="18" :strokeWidth="2" strokeLinecap="square" />
							</div>
						</el-button>
					</div>
				</div>
			</div>
		</el-card>
		<slot name="nav-tab"></slot>
		<div class="operate" v-if="actionBtn">
			<div class="menu-left">
				<!-- 用于综合查询打开全字段查询 -->
				<el-switch
					v-if="isComprehensiveQueries"
					style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949; margin-right: 20px"
					active-text="打开全字段查询"
					inactive-text="关闭全字段查询"
					v-model="isOpenQuery"
				/>

				<!--  -->
				<el-button v-if="auth.add && !isComprehensiveQueries" v-auth="auth.add" type="primary" @click="handleOperate('add', {}, `${addLabel}数据`)">
					<icon-add-one theme="outline" class="mr8" :strokeWidth="2" strokeLinecap="square" />
					{{ addLabel }}
				</el-button>
				<slot v-if="!isComprehensiveQueries" name="group-btn"></slot>
				<el-button v-if="auth.import && !isComprehensiveQueries" v-auth="auth.import" @click="handleOperate('import', {}, '导入')">
					<el-icon class="el-icon--right mr8">
						<Upload />
					</el-icon>
					{{ api.importLabel || '批量采集' }}
				</el-button>
				<AplidActions v-if="menuAction && !isComprehensiveQueries" :list="menuAction" @change="handleOperate"> </AplidActions>
				<el-button @click="handleOperate('refresh', {}, '刷新')" class="mr8" v-if="searchConfig">
					<icon-refresh class="mr8" :strokeWidth="2" />
					刷新
				</el-button>
				<MulitSet
					v-if="auth.mulitSet"
					:exportApi="api.export"
					:rowKey="rowKey"
					:businessRowKey="businessRowKey"
					:paramsObj="{ ...paramsObj, ...searchFormateMod }"
					:auth="auth"
					:api="api"
					:exportMqTopic="exportMqTopic"
					:multipleSelection="multipleSelection"
					:noMulDel="noMulDel"
					@cancel="handleCancelSelect"
					@delete="handleOperate"
					@refresh="handleOperate('refresh', {}, '刷新')"
				></MulitSet>
				<slot v-if="!isComprehensiveQueries" name="menuLeftAppend"></slot>
			</div>
			<div v-if="!isComprehensiveQueries" class="menu-right">
				<slot name="menuRight"></slot>
			</div>
		</div>
		<!-- 综合查询的全字段查询 -->
		<AplidForm :key="openCloseChange" v-show="isComprehensiveQueries && isOpenQuery" v-bind="eightMoreSearchConfig" v-model="searchModel"></AplidForm>
		<div class="search_action" v-if="isComprehensiveQueries && isOpenQuery">
			<el-button @click="onSearch(searchModel, () => {}, activeName == 'first' ? 'more' : 'reserve')" type="primary">查询</el-button>
			<el-button @click="onReset()">重置</el-button>
			<span class="open_text" @click="openHandle">{{ isOpenMore ? '收起' : '展开' }}</span>
		</div>
		<!--  -->
		<ApldTable
			ref="tableRef"
			v-loading="tableLoading"
			v-if="layout == 'table'"
			v-bind="{ rowKey, ...tableConfig, ...$attrs }"
			:pageSize="pageReac.size"
			:pageCurrent="pageReac.current"
			:auth="auth"
			:data="tableData"
			:key="reloadTable"
			@selection-change="handleSelectionChange"
		>
			<template v-for="(_, key) in slotAttr" v-slot:[key]="{ row }">
				<slot :name="key" :row="row"></slot>
			</template>
			<template v-slot:menu="{ row }">
				<AplidActions v-if="menuBtn" :list="menuBtn" @change="handleOperate" :auth="auth" :row="row"> </AplidActions>
				<slot name="menuColumn" :row="row"></slot>
			</template>
		</ApldTable>
		<CardTable v-else-if="layout === 'card'" :tableData="tableData" :menuBtn="menuBtn" @change="handleOperate">
			<template v-for="(_, key) in slotAttr" v-slot:[key]="{ row }">
				<slot :name="key" :row="row"></slot>
			</template>
		</CardTable>
		<slot v-else name="table" :tableData="tableData"></slot>
		<AplidPaginate v-bind="pageReac" @change="onPageChange" class="pageinate" />
		<aplid-dialog
			v-if="visibleForm"
			width="65%"
			v-model="visibleForm"
			:title="dialogTitle"
			append-to-body
			:close-on-click-modal="false"
			:pageName="pageName || route.meta?.title"
			v-bind="dialogConfig"
			@close="handleOnClose"
			@open="hanleOpenDialog"
			:whickComm="whickComm"
			:customeHeader="detailConfig?.customeHeader"
			:model="{ ...nowRowData, ...detailHeadData }"
		>
			<transition name="fade" mode="out-in">
				<div class="dialog-content w-100" v-show="!Loading">
					<slot
						v-if="Object.keys(slotAttr).includes(`${whickComm}Dialog`) && visibleForm"
						:name="`${whickComm}Dialog`"
						:type="whickComm"
						:show="1"
						:row="nowRowData"
					></slot>
					<ImportForm
						:nowRowData="nowRowData"
						v-else-if="whickComm == 'import'"
						v-bind="importConfig"
						@refreshPage="visibleForm = !visibleForm"
					></ImportForm>
					<DetailPage :model="nowRowData" :nowRowData="nowRowData" v-bind="detailConfig" v-else-if="whickComm == 'detail'">
						<template v-for="(_, key) in slotAttr" v-slot:[key]="{ row }">
							<slot :name="`${key}Detail`" :row="row" :show="1" :model="nowRowData"></slot>
						</template>
					</DetailPage>
					<AplidForm
						v-else-if="formConfig"
						:key="visibleForm"
						v-bind="formConfig"
						:rowKey="rowKey"
						v-model="nowRowData"
						@submit="onSubmit"
						@reset="visibleForm = !visibleForm"
					>
						<template v-for="(_, key) in slotAttr" v-slot:[key]="{ row }">
							<slot :name="key" :row="row" :show="1" :model="nowRowData"></slot>
						</template>
					</AplidForm>
					<slot name="detail-btn" :row="nowRowData"></slot>
				</div>
			</transition>
			<PageLoading v-if="Loading" />
		</aplid-dialog>

		<el-drawer v-model="drawer" :close-on-click-modal="false" title="全字段查询" size="600px" :lock-scroll="false" :modal="false" append-to-body>
			<div v-if="!slotAttr.moreSearch && drawer">
				<el-tabs v-model="activeName" @tab-change="moreSearchChange">
					<el-tab-pane v-if="moreSearchConfig" label="信息查询" name="first">
						<AplidForm v-bind="moreSearchConfig" v-show="drawer" v-model="searchModel" :showRules="false"></AplidForm>
					</el-tab-pane>
					<el-tab-pane v-if="reserveSearchConfig" label="信息采集查缺补漏" name="second">
						<AplidForm v-bind="reserveSearchConfig" v-show="drawer" v-model="searchModel" :showRules="false"></AplidForm>
					</el-tab-pane>
				</el-tabs>
			</div>
			<!-- 插槽 -->
			<slot v-if="slotAttr.moreSearch" name="moreSearch" :show="drawer"></slot>

			<template #footer v-if="!slotAttr.moreSearch">
				<div style="flex: auto">
					<el-button @click="onReset">重置</el-button>
					<el-button type="primary" v-if="activeName == 'first'" @click="handleMoreSearch"> 查询 </el-button>
					<el-button type="primary" v-else @click="toMoreSearsh"> 查询 </el-button>
				</div>
			</template>
		</el-drawer>
		<!-- es查询 -->
		<!-- <el-drawer v-model="drawer" :close-on-click-modal="false" title="全字段查询" size="600px" :lock-scroll="false" :modal="false" append-to-body>
			<div v-if="!slotAttr.moreSearch">
				<el-tabs v-model="activeName" @tab-change="moreSearchChange">
					<el-tab-pane v-if="moreSearchConfig" label="信息查询" name="first"></el-tab-pane>
					<el-tab-pane v-if="reserveSearchConfig" label="信息采集查缺补漏" name="second"></el-tab-pane>
				</el-tabs>
				<AplidForm v-if="moreSearchConfig && activeName == 'first'" v-bind="moreSearchConfig" v-show="drawer" v-model="searchModel"></AplidForm>
				<AplidForm
					v-if="reserveSearchConfig && activeName == 'second'"
					v-bind="reserveSearchConfig"
					v-show="drawer"
					v-model="searchModel"
				></AplidForm>
			</div>
			<slot v-if="slotAttr.moreSearch" name="moreSearch" :show="drawer"></slot>

			<template #footer v-if="!slotAttr.moreSearch">
				<div style="flex: auto">
					<el-button @click="onReset">重置</el-button>
					<el-button type="primary" @click="toMoreSearsh"> 查询 </el-button>
				</div>
			</template>
		</el-drawer> -->
	</div>
</template>

<script setup lang="ts">
import DateBetween from '@/views/aplid/DateBetween/index.vue'
import { useCrud } from '@/hooks/useCrudHooks'
import { ApldTable, AplidPaginate, AplidActions } from '@/components/AplidCrud'
import { Search, Refresh, Upload } from '@element-plus/icons-vue'
import ImportForm from './ImportForm/index.vue'
import DetailPage from '@/views/aplid/DetailPage/index.vue'
import CardTable from './CardTable/index.vue'
import MulitSet from './MulitSet/index.vue'
import { useSlots } from 'vue'
import { useCommonStore } from '@/stores/common'
import { useCrudStore } from '@/stores/crud'
import apiMod from '@/apiMod/index'
import { apiModType } from '@/types/crud.types'
const { Loading, detailHeadData } = storeToRefs(useCommonStore())

let { tableLoading } = storeToRefs(useCrudStore())

const emit = defineEmits(['getTableData', 'getDataTotal', 'dialog-close'])

const route = useRoute()
const router = useRouter()
const slotAttr = useSlots()
const attrs = useAttrs()

interface IMqTopic {
	code: number
	po: string
	[propName: string]: any
}

type Props = {
	layout?: string
	pageName: string
	loadOrgInfo?: boolean // 是否加载org 信息
	showHeaderTitle?: boolean
	rowKey?: string
	businessRowKey?: string
	tipLabel?: string
	addLabel?: string
	exportMqTopic?: string | Array<IMqTopic>
	dictcodes?: Object[] | string
	api: apiModType
	auth: any
	menuBtn?: any
	menuAction?: any
	paramsObj?: any
	tableConfig: any
	searchConfig?: any
	formConfig?: any
	detailConfig?: any
	moreSearchConfig?: any
	reserveSearchConfig?: any
	dialogConfig?: any
	importConfig?: any
	saveFormate?: Function
	operateFormate?: Function
	onLoadFormate?: Function
	operateBefore?: Function
	beforeOnLoadFormate?: Function
	actionBtn?: boolean
	openMore?: boolean
	isComprehensiveQueries?: boolean
	needPigeonhole?: boolean
	noMulDel?:boolean // 是否没有批量删除
}

const props = withDefaults(defineProps<Props>(), {
	rowKey: 'id',
	addLabel: '采集数据',
	actionBtn: true,
	layout: 'table',
	isComprehensiveQueries: false,
	needPigeonhole: false,
	showHeaderTitle: true,
	noMulDel:false
})
const tableRef = ref(null)

const allExport = () => {
	let params = {}
	if (typeof props.exportMqTopic == 'string') {
		// 处理参数
		params['queryCondition'] = searchModel.value ? { ...searchModel.value } : undefined
		params['code'] = props.paramsObj.code
	} else {
		// 处理参数
		props.exportMqTopic.forEach((el) => {
			params[el.po] = { code: el.code }
		})
		// 只有服务对象能用到
		params['queryCondition'] = searchModel.value ? { ...searchModel.value, seniorLiving: props.paramsObj?.seniorLiving } : undefined
	}
	apiMod[props.api.export](params).then((res) => {
		ElMessage.success('操作成功')
	})
}
let activeName = ref('first')
// 去往数据统计
const toDataStatistics = () => {}
const searchRef = ref(null)
const searchModel = ref({})
const drawer = ref(false)
// 综合查询中，是否打开全字段查询
let isOpenQuery = ref(false)
let isOpenMore = ref(false)
const toMoreSearsh = () => {
	onSearch(searchModel.value, () => {}, activeName.value == 'first' ? 'more' : 'reserve')
}

const handleMoreSearch = () => {
	onSearch(searchModel.value, () => {})
}
// 展示拿到前8个，点击展开才显示
let eightMoreSearchConfig = ref({})
let copyMoreSearchConfig: any = {}
let openCloseChange = ref(1)
if (props.isComprehensiveQueries) {
	if (props.moreSearchConfig) {
		copyMoreSearchConfig = JSON.parse(JSON.stringify(props.moreSearchConfig))
		copyMoreSearchConfig.column = copyMoreSearchConfig.column.slice(0, 8)
		eightMoreSearchConfig.value = copyMoreSearchConfig
		openCloseChange.value = Math.random()
	}
}

// 展开收起处理
const openHandle = () => {
	if (isOpenMore.value) {
		copyMoreSearchConfig.column = copyMoreSearchConfig.column.slice(0, 8)
		eightMoreSearchConfig.value = copyMoreSearchConfig
		isOpenMore.value = false
		openCloseChange.value = Math.random()
	} else {
		eightMoreSearchConfig.value = props.moreSearchConfig
		isOpenMore.value = true
		openCloseChange.value = Math.random()
	}
}
// 用于综合查询时的全字段搜索
watch(
	() => props.openMore,
	(newVal) => {
		drawer.value = newVal
	}
)
drawer.value = props.openMore
const onReset = () => {
	searchModel.value = {}
	setMoreSearch({})
	onSearch(searchModel.value)
}

// 全字段查询时切换tab页要清空之前的搜索条件
const moreSearchChange = () => {
	searchModel.value = {}
	setMoreSearch({})
}
const handleOnClose = () => {
	emit('dialog-close', whickComm.value)
	if (whickComm.value !== 'detail') {
		setMoreSearch({})
	}
	// 弹窗关闭刷新字典数据
	hanleOpenDialog()
	refreshChange({}, false)
}

let pigeonholeTime = ref('')

const handleTimeChange = () => {
	router.push({
		path: '/placeOnFile',
		query: {
			time: pigeonholeTime.value,
			apiIndex: props.api.index,
		},
	})
}

const onLoadFormate = (arr, data) => {
	setTimeout(() => {
		if (attrs.selectedData) {
			tableRef.value?.toggleSelection(attrs.selectedData, true)
		}
	}, 200)
	emit('getTableData', arr)
	emit('getDataTotal', data.total)
	return props.onLoadFormate ? props.onLoadFormate(arr, data) : arr
}

const setToggleSelection = (data) => {
	tableRef.value?.toggleSelection(data, true, true)
}
const {
	reloadTable,
	multipleSelection,
	hanleOpenDialog,
	visibleForm,
	nowRowData,
	dialogTitle,
	tableData,
	pageReac,
	whickComm,
	searchFormateMod,
	setMoreSearch,
	handleOperate,
	onPageChange,
	onSearch,
	onSubmit,
	refreshChange,
	handleSelectionChange,
	handleCancelSelect,
} = useCrud({
	api: props.api,
	pageName: props.pageName,
	loadOrgInfo: props.loadOrgInfo,
	dictcodes: props.dictcodes,
	rowKey: props.rowKey,
	tipLabel: props.tipLabel,
	paramsObj: props.paramsObj,
	saveFormate: props.saveFormate,
	operateFormate: props.operateFormate,
	onLoadFormate: onLoadFormate,
	operateBefore: props.operateBefore,
	beforeOnLoadFormate: props.beforeOnLoadFormate,
	defaultTableData: props.tableConfig.data,
	searchConfig: props.searchConfig,
})

defineExpose({
	setToggleSelection,
	handleOperate,
	refreshChange,
	multipleSelection,
})
</script>

<style scoped lang="scss">
@import '@/styles/scss/ap-container.scss';
.pigeonhole_part {
	display: flex;
	flex-direction: row;
	justify-content: flex-start;
	align-items: center;
}
.search_action {
	width: 200px;
	margin: 21px auto;
	display: flex;
	flex-direction: row;
	justify-content: space-around;
	align-items: center;
}
.open_text {
	font-weight: 400;
	font-size: 14px;
	text-align: left;
	color: #0052d9;
	cursor: pointer;
}
</style>
